<template>
  <div class="category-container">
    <!-- 权限不足提示 -->
    <el-alert
      v-if="!hasReadPermission"
      title="权限不足"
      type="warning"
      description="您没有访问分类管理的权限，请联系管理员分配 category:read 权限。"
      show-icon
      :closable="false"
      class="permission-alert"
    >
      <template #default>
        <div class="permission-content">
          <p><strong>权限不足</strong></p>
          <p>您没有访问分类管理的权限，需要以下权限：</p>
          <ul>
            <li><code>category:read</code> - 查看分类列表</li>
            <li><code>category:create</code> - 创建分类</li>
            <li><code>category:update</code> - 编辑分类</li>
            <li><code>category:delete</code> - 删除分类</li>
          </ul>
          <p>请联系系统管理员分配相应权限。</p>
        </div>
      </template>
    </el-alert>

    <!-- 主要内容区域 -->
    <template v-if="hasReadPermission">
      <!-- 页面头部 -->
      <PageHeader
        title="栏目管理"
        subtitle="分类管理"
        description="管理网站的栏目分类，支持多级分类结构和权限控制"
        icon="FolderOpened"
        :show-extra="true"
        :show-refresh="true"
        :stats="headerStats"
        @refresh="handleRefresh"
      />

      <!-- 操作工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button 
            v-if="hasCreatePermission"
            type="primary" 
            @click="handleAdd" 
            :icon="Plus"
            :loading="loading"
          >
            添加顶级栏目
          </el-button>
          
          <el-button 
            @click="handleRefresh" 
            :icon="Refresh"
            :loading="loading"
          >
            刷新数据
          </el-button>
          
          <el-button 
            v-if="hasDeletePermission"
            type="danger" 
            @click="handleBatchDelete" 
            :disabled="!hasSelection || loading" 
            :icon="Delete"
          >
            批量删除 {{ hasSelection ? `(${selectedRows.length})` : '' }}
          </el-button>
          
          <el-button 
            v-if="hasUpdatePermission"
            type="warning" 
            @click="handleBatchToggle" 
            :disabled="!hasSelection || loading"
            :icon="View"
          >
            批量操作
          </el-button>

          <el-dropdown v-if="hasSelection && (hasDeletePermission || hasUpdatePermission)">
            <el-button :icon="ArrowDown" :disabled="loading">
              更多操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  v-if="hasUpdatePermission"
                  @click="handleBatchShow"
                  :disabled="loading"
                >
                  <el-icon><View /></el-icon>
                  批量显示
                </el-dropdown-item>
                <el-dropdown-item 
                  v-if="hasUpdatePermission"
                  @click="handleBatchHide"
                  :disabled="loading"
                >
                  <el-icon><Hide /></el-icon>
                  批量隐藏
                </el-dropdown-item>
                <el-dropdown-item 
                  @click="handleBatchExport"
                  :disabled="loading"
                >
                  <el-icon><Download /></el-icon>
                  导出选中
                </el-dropdown-item>
                <el-dropdown-item 
                  v-if="hasDeletePermission"
                  divided
                  @click="handleBatchDelete"
                  :disabled="loading"
                >
                  <el-icon><Delete /></el-icon>
                  删除选中
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        
        <div class="toolbar-right">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入栏目名称搜索"
            style="width: 280px"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button 
                @click="handleSearch" 
                :icon="Search" 
                :loading="searchLoading"
              />
            </template>
          </el-input>
        </div>
      </div>

      <!-- 统计信息卡片 -->
      <div class="stats-cards" v-if="total > 0">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <el-statistic title="总栏目数" :value="total">
                <template #suffix>
                  <el-icon style="vertical-align: -0.125em; color: #409eff">
                    <FolderOpened />
                  </el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <el-statistic title="顶级栏目" :value="topLevelCount">
                <template #suffix>
                  <el-icon style="vertical-align: -0.125em; color: #67c23a">
                    <Folder />
                  </el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <el-statistic title="已选择" :value="selectedRows.length">
                <template #suffix>
                  <el-icon style="vertical-align: -0.125em; color: #e6a23c">
                    <Select />
                  </el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <el-statistic title="隐藏栏目" :value="hiddenCount">
                <template #suffix>
                  <el-icon style="vertical-align: -0.125em; color: #f56c6c">
                    <Hide />
                  </el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分类表格 -->
      <div class="table-container">
        <!-- 表格工具栏 -->
        <div class="table-toolbar">
          <div class="toolbar-left">
            <span class="toolbar-title">分类列表</span>
            <el-divider direction="vertical" />
            <el-text size="small" type="info">
              共 {{ total }} 条记录
              <span v-if="hasSelection">，已选择 {{ selectedRows.length }} 条</span>
            </el-text>
          </div>
          <div class="toolbar-right">
            <el-tooltip content="刷新表格" placement="top">
              <el-button 
                :icon="Refresh" 
                circle 
                @click="handleRefresh"
                :loading="loading"
              />
            </el-tooltip>
            <el-tooltip content="表格设置" placement="top">
              <el-button 
                :icon="Setting" 
                circle 
                @click="handleTableSettings"
              />
            </el-tooltip>
          </div>
        </div>

        <el-table
          ref="tableRef"
          :data="categoryList"
          v-loading="loading"
          row-key="id"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
          border
          stripe
          class="category-table"
          empty-text="暂无分类数据"
          element-loading-text="正在加载分类数据..."
          element-loading-spinner="el-icon-loading"
          height="calc(100vh - 580px)"
        >
          <!-- 选择列 -->
          <el-table-column 
            type="selection" 
            width="50" 
            align="center"
            :selectable="checkSelectable"
          />
          
          <!-- 序号列 -->
          <el-table-column label="序号" width="80" align="center">
            <template #default="{ $index }">
              <el-tag type="info" size="small">{{ $index + 1 }}</el-tag>
            </template>
          </el-table-column>

          <!-- 栏目ID -->
          <el-table-column 
            label="栏目ID" 
            prop="id" 
            width="120" 
            align="center" 
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <el-text size="small" type="primary" tag="code">{{ row.id }}</el-text>
            </template>
          </el-table-column>

          <!-- 栏目名称 -->
          <el-table-column 
            label="栏目名称" 
            prop="name" 
            min-width="200" 
            show-overflow-tooltip
            sortable
          >
            <template #default="{ row }">
              <div class="category-name">
                <el-icon 
                  v-if="row.children && row.children.length" 
                  class="expand-icon" 
                  color="#409eff"
                  size="18"
                >
                  <FolderOpened />
                </el-icon>
                <el-icon 
                  v-else 
                  class="expand-icon" 
                  color="#67c23a"
                  size="18"
                >
                  <Document />
                </el-icon>
                
                <span class="name-text">{{ row.name }}</span>
                
                <el-tag 
                  v-if="row.level" 
                  size="small" 
                  type="info" 
                  class="level-tag"
                  effect="plain"
                >
                  L{{ row.level }}
                </el-tag>
                
                <el-tag 
                  v-if="row.isHot" 
                  size="small" 
                  type="danger" 
                  class="hot-tag"
                  effect="plain"
                >
                  热门
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <!-- 英文名称 -->
          <el-table-column 
            label="英文名称" 
            prop="englishName" 
            width="150" 
            align="center" 
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <el-text 
                class="english-name" 
                type="info" 
                style="font-style: italic;"
              >
                {{ row.englishName || '-' }}
              </el-text>
            </template>
          </el-table-column>

          <!-- 描述 -->
          <el-table-column 
            label="描述" 
            prop="description" 
            width="200" 
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <el-text size="small" v-if="row.description">
                {{ row.description }}
              </el-text>
              <el-text size="small" type="info" v-else>暂无描述</el-text>
            </template>
          </el-table-column>

          <!-- 允许投稿 -->
          <el-table-column label="允许投稿" width="100" align="center">
            <template #default="{ row }">
              <el-tag 
                :type="row.allowSubmit ? 'success' : 'danger'" 
                size="small"
                effect="plain"
              >
                {{ row.allowSubmit ? '允许' : '禁止' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 显示状态 -->
          <el-table-column label="显示状态" width="100" align="center">
            <template #default="{ row }">
              <el-switch
                v-if="hasUpdatePermission"
                v-model="row.isVisible"
                @change="handleVisibilityChange(row)"
                :active-value="true"
                :inactive-value="false"
                :loading="row.loading"
                inline-prompt
                active-text="显"
                inactive-text="隐"
                size="small"
              />
              <el-tag 
                v-else
                :type="row.isVisible ? 'success' : 'danger'" 
                size="small"
                effect="plain"
              >
                {{ row.isVisible ? '显示' : '隐藏' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 排序 -->
          <el-table-column label="排序" width="100" align="center" sortable="custom">
            <template #default="{ row }">
              <el-input-number
                v-if="hasUpdatePermission"
                v-model="row.sort"
                :min="0"
                :max="9999"
                :step="1"
                size="small"
                controls-position="right"
                style="width: 90px"
                @change="handleSortChange(row)"
                @blur="handleSortBlur(row)"
              />
              <el-text v-else size="small" type="primary">{{ row.sort }}</el-text>
            </template>
          </el-table-column>

          <!-- 文章数量 -->
          <el-table-column label="文章数" width="80" align="center" sortable="custom">
            <template #default="{ row }">
              <el-link 
                type="primary" 
                @click="handleViewArticles(row)"
                :underline="false"
              >
                {{ row.articleCount || 0 }}
              </el-link>
            </template>
          </el-table-column>

          <!-- 创建时间 -->
          <el-table-column 
            label="创建时间" 
            prop="createTime" 
            width="160" 
            align="center"
            sortable="custom"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              <el-text size="small">{{ formatDate(row.createTime) }}</el-text>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column 
            label="操作" 
            width="320" 
            align="center" 
            fixed="right"
          >
            <template #default="{ row }">
              <div class="action-buttons">
                <!-- 添加子栏目 -->
                <el-tooltip content="添加子栏目" placement="top">
                  <el-button
                    v-if="hasCreatePermission"
                    type="success"
                    size="small"
                    @click="handleAddChild(row)"
                    :icon="Plus"
                    circle
                  />
                </el-tooltip>
                
                <!-- 查看详情 -->
                <el-tooltip content="查看详情" placement="top">
                  <el-button
                    type="info"
                    size="small"
                    @click="handleView(row)"
                    :icon="View"
                    circle
                  />
                </el-tooltip>
                
                <!-- 编辑 -->
                <el-tooltip content="编辑栏目" placement="top">
                  <el-button
                    v-if="hasUpdatePermission"
                    type="primary"
                    size="small"
                    @click="handleEdit(row)"
                    :icon="Edit"
                    circle
                  />
                </el-tooltip>
                
                <!-- 复制 -->
                <el-tooltip content="复制栏目" placement="top">
                  <el-button
                    v-if="hasCreatePermission"
                    type="warning"
                    size="small"
                    @click="handleCopy(row)"
                    :icon="CopyDocument"
                    circle
                  />
                </el-tooltip>
                
                <!-- 更多操作下拉菜单 -->
                <el-dropdown @command="(command) => handleMoreAction(command, row)">
                  <el-button 
                    size="small" 
                    :icon="More"
                    circle
                  />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item 
                        command="move" 
                        v-if="hasUpdatePermission"
                        :icon="Rank"
                      >
                        移动栏目
                      </el-dropdown-item>
                      <el-dropdown-item 
                        command="seo" 
                        v-if="hasUpdatePermission"
                        :icon="Search"
                      >
                        SEO设置
                      </el-dropdown-item>
                      <el-dropdown-item 
                        command="permission" 
                        v-if="hasUpdatePermission"
                        :icon="Key"
                      >
                        权限设置
                      </el-dropdown-item>
                      <el-dropdown-item 
                        command="export" 
                        :icon="Download"
                      >
                        导出数据
                      </el-dropdown-item>
                      <el-dropdown-item 
                        divided
                        command="delete" 
                        v-if="hasDeletePermission && (!row.children || row.children.length === 0)"
                        :icon="Delete"
                      >
                        <span style="color: #f56c6c;">删除栏目</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <TablePagination
          v-if="total > 0"
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :total="total"
          :selection-count="selectedRows.length"
          :show-selection="true"
          :show-batch-actions="hasDeletePermission || hasUpdatePermission"
          :show-size-hint="true"
          @page-change="handlePageChange"
          @size-change="handlePageSizeChange"
        >
          <template #batch-actions="{ selectionCount }">
            <el-button
              v-if="hasDeletePermission"
              type="danger"
              size="small"
              :disabled="selectionCount === 0"
              @click="handleBatchDelete"
            >
              删除选中 ({{ selectionCount }})
            </el-button>
            <el-button
              v-if="hasUpdatePermission"
              type="warning"
              size="small"
              :disabled="selectionCount === 0"
              @click="handleBatchHide"
            >
              批量隐藏
            </el-button>
            <el-button
              v-if="hasUpdatePermission"
              type="success"
              size="small"
              :disabled="selectionCount === 0"
              @click="handleBatchShow"
            >
              批量显示
            </el-button>
            <el-button
              type="info"
              size="small"
              :disabled="selectionCount === 0"
              @click="handleBatchExport"
            >
              导出选中
            </el-button>
          </template>
        </TablePagination>
      </div>
    </template>

    <!-- 分类对话框 -->
    <CategoryDialog
      v-if="hasReadPermission"
      v-model="dialogVisible"
      :category="currentCategory"
      :parent-id="parentId"
      :category-list="flatCategoryList"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
  Plus,
  Refresh,
  Delete,
  Search,
  Edit,
  View,
  Hide,
  FolderOpened,
  Document,
  Folder,
  Select,
  Setting,
  ArrowDown,
  Download,
  CopyDocument,
  More,
  Rank,
  Key
} from '@element-plus/icons-vue'
import { categoryApi } from '@/api/category'
import { hasPermission } from '@/utils/permission'
import PageHeader from '@/components/common/PageHeader.vue'
import TablePagination from '@/components/common/TablePagination.vue'
import CategoryDialog from '@/components/category/CategoryDialog.vue'

// 权限检查
const hasReadPermission = computed(() => hasPermission('category:read'))
const hasCreatePermission = computed(() => hasPermission('category:create'))
const hasUpdatePermission = computed(() => hasPermission('category:update'))
const hasDeletePermission = computed(() => hasPermission('category:delete'))

// 响应式数据
const loading = ref(false)
const searchLoading = ref(false)
const categoryList = ref([])
const flatCategoryList = ref([])
const total = ref(0)
const selectedRows = ref([])
const searchKeyword = ref('')
const dialogVisible = ref(false)
const currentCategory = ref(null)
const parentId = ref(null)
const tableRef = ref()

// 查询参数
const queryParams = reactive({
  page: 1,
  size: 20,
  keyword: '',
  level: null,
  sortBy: 'sort',
  sortOrder: 'asc'
})

// 计算属性
const hasSelection = computed(() => selectedRows.value.length > 0)

const topLevelCount = computed(() => 
  flatCategoryList.value.filter(item => !item.parentId).length
)

const hiddenCount = computed(() => 
  flatCategoryList.value.filter(item => !item.isVisible).length
)

const headerStats = computed(() => [
  {
    label: '总栏目数',
    value: total.value,
    icon: 'FolderOpened',
    color: '#409eff',
    clickable: true
  },
  {
    label: '顶级栏目',
    value: topLevelCount.value,
    icon: 'Folder',
    color: '#67c23a',
    clickable: true
  },
  {
    label: '已选择',
    value: selectedRows.value.length,
    icon: 'Select',
    color: '#e6a23c',
    clickable: false
  },
  {
    label: '隐藏栏目',
    value: hiddenCount.value,
    icon: 'Hide',
    color: '#f56c6c',
    clickable: true
  }
])

// 生命周期
onMounted(() => {
  if (hasReadPermission.value) {
    fetchCategoryList()
  } else {
    ElMessage.warning('权限不足，无法加载分类数据')
  }
})

// 获取分类列表
const fetchCategoryList = async () => {
  if (!hasReadPermission.value) {
    ElMessage.error('权限不足，无法读取分类数据')
    return
  }

  try {
    loading.value = true
    const params = {
      ...queryParams,
      keyword: searchKeyword.value
    }
    
    const response = await categoryApi.getList(params)
    
    if (response.code === 200) {
      categoryList.value = buildTree(response.data.items)
      flatCategoryList.value = response.data.items
      total.value = response.data.total
    }
  } catch (error) {
    console.error('Error fetching categories:', error)
    
    if (error.message && !error.message.includes('权限不足')) {
      ElMessage.error('获取分类列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 构建树形结构
const buildTree = (items) => {
  const tree = []
  const itemMap = {}
  
  items.forEach(item => {
    itemMap[item.id] = { 
      ...item, 
      children: [],
      loading: false,
      originalSort: item.sort
    }
  })
  
  items.forEach(item => {
    if (item.parentId && itemMap[item.parentId]) {
      itemMap[item.parentId].children.push(itemMap[item.id])
    } else {
      tree.push(itemMap[item.id])
    }
  })
  
  return tree
}

// 检查是否可选择
const checkSelectable = (row) => {
  // 可以根据具体业务需求添加选择限制
  return true
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 事件处理方法
const handleSearch = async () => {
  if (!hasReadPermission.value) return
  
  searchLoading.value = true
  queryParams.page = 1
  
  try {
    await fetchCategoryList()
  } finally {
    searchLoading.value = false
  }
}

const handleRefresh = async () => {
  if (!hasReadPermission.value) return
  
  ElNotification({
    title: '刷新成功',
    message: '分类数据已更新',
    type: 'success',
    duration: 2000
  })
  
  await fetchCategoryList()
}

const handleAdd = () => {
  if (!hasCreatePermission.value) {
    ElMessage.error('权限不足，无法创建分类')
    return
  }
  
  currentCategory.value = null
  parentId.value = null
  dialogVisible.value = true
}

const handleAddChild = (row) => {
  if (!hasCreatePermission.value) {
    ElMessage.error('权限不足，无法创建子分类')
    return
  }
  
  currentCategory.value = null
  parentId.value = row.id
  dialogVisible.value = true
}

const handleEdit = (row) => {
  if (!hasUpdatePermission.value) {
    ElMessage.error('权限不足，无法编辑分类')
    return
  }
  
  currentCategory.value = { ...row }
  parentId.value = row.parentId
  dialogVisible.value = true
}

const handleView = (row) => {
  const createTimeStr = formatDate(row.createTime)
  const updateTimeStr = formatDate(row.updateTime)
  
  ElMessageBox.alert(
    `<div style="text-align: left; line-height: 1.6;">
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">栏目ID:</strong>
        <span style="color: #409eff; font-family: monospace;">${row.id}</span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">栏目名称:</strong>
        <span>${row.name}</span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">英文名称:</strong>
        <span style="font-style: italic; color: #666;">${row.englishName || '未设置'}</span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">描述:</strong>
        <span style="color: #666;">${row.description || '无描述'}</span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">级别:</strong>
        <span>${row.level || '未设置'}</span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">排序:</strong>
        <span>${row.sort}</span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">显示状态:</strong>
        <span style="color: ${row.isVisible ? '#67c23a' : '#f56c6c'};">
          ${row.isVisible ? '✓ 显示' : '✗ 隐藏'}
        </span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">允许投稿:</strong>
        <span style="color: ${row.allowSubmit ? '#67c23a' : '#f56c6c'};">
          ${row.allowSubmit ? '✓ 允许' : '✗ 禁止'}
        </span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">文章数量:</strong>
        <span>${row.articleCount || 0} 篇</span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">SEO关键词:</strong>
        <span style="color: #666;">${row.seoKeywords || '未设置'}</span>
      </div>
      <div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">创建时间:</strong>
        <span style="color: #666;">${createTimeStr}</span>
      </div>
      ${updateTimeStr !== '-' ? `<div style="display: flex; margin-bottom: 12px;">
        <strong style="width: 100px; flex-shrink: 0;">更新时间:</strong>
        <span style="color: #666;">${updateTimeStr}</span>
      </div>` : ''}
    </div>`,
    '栏目详情',
    {
      confirmButtonText: '知道了',
      dangerouslyUseHTMLString: true,
      customClass: 'category-detail-dialog',
      width: '500px'
    }
  )
}

const handleCopy = (row) => {
  if (!hasCreatePermission.value) {
    ElMessage.error('权限不足，无法复制分类')
    return
  }
  
  const copyData = {
    ...row,
    id: null,
    name: `${row.name}_副本`,
    englishName: row.englishName ? `${row.englishName}_copy` : '',
    children: undefined
  }
  
  currentCategory.value = copyData
  parentId.value = row.parentId
  dialogVisible.value = true
}

const handleMoreAction = (command, row) => {
  switch (command) {
    case 'move':
      ElMessage.info('移动栏目功能开发中...')
      break
    case 'seo':
      ElMessage.info('SEO设置功能开发中...')
      break
    case 'permission':
      ElMessage.info('权限设置功能开发中...')
      break
    case 'export':
      handleExportSingle(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      break
  }
}

const handleDelete = (row) => {
  if (!hasDeletePermission.value) {
    ElMessage.error('权限不足，无法删除分类')
    return
  }
  
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该分类下有子分类，无法删除')
    return
  }
  
  if (row.articleCount > 0) {
    ElMessage.warning(`该分类下有 ${row.articleCount} 篇文章，请先移动文章后再删除`)
    return
  }
  
  ElMessageBox.confirm(
    `<div style="text-align: left;">
      <p style="margin-bottom: 12px;">确定要删除栏目 <strong style="color: #f56c6c;">"${row.name}"</strong> 吗？</p>
      <p style="color: #666; font-size: 14px; margin-bottom: 8px;">此操作将：</p>
      <ul style="color: #666; font-size: 14px; margin: 0; padding-left: 20px;">
        <li>永久删除该栏目</li>
        <li>无法恢复栏目数据</li>
      </ul>
      <p style="color: #f56c6c; font-size: 14px; margin-top: 12px; font-weight: bold;">
        ⚠️ 此操作不可恢复！
      </p>
    </div>`,
    '确认删除',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error',
      buttonSize: 'default',
      dangerouslyUseHTMLString: true,
      customClass: 'delete-confirm-dialog'
    }
  ).then(async () => {
    try {
      const response = await categoryApi.delete(row.id)
      if (response.code === 200) {
        ElNotification({
          title: '删除成功',
          message: `栏目"${row.name}"已被删除`,
          type: 'success'
        })
        await fetchCategoryList()
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

const handleBatchDelete = () => {
  if (!hasDeletePermission.value) {
    ElMessage.error('权限不足，无法删除分类')
    return
  }
  
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的栏目')
    return
  }
  
  const hasChildren = selectedRows.value.some(row => row.children && row.children.length > 0)
  if (hasChildren) {
    ElMessage.warning('选中的栏目中包含有子分类的项目，无法批量删除')
    return
  }
  
  const hasArticles = selectedRows.value.some(row => (row.articleCount || 0) > 0)
  if (hasArticles) {
    ElMessage.warning('选中的栏目中包含有文章的项目，请先移动文章后再删除')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个栏目吗？此操作不可恢复。`,
    '批量删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error',
      buttonSize: 'default'
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      const response = await categoryApi.batchDelete(ids)
      if (response.code === 200) {
        ElNotification({
          title: '批量删除成功',
          message: `成功删除 ${selectedRows.value.length} 个栏目`,
          type: 'success'
        })
        selectedRows.value = []
        await fetchCategoryList()
      }
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  })
}

const handleBatchToggle = () => {
  const visibleCount = selectedRows.value.filter(row => row.isVisible).length
  const hiddenCount = selectedRows.value.length - visibleCount
  
  ElMessageBox.confirm(
    `选中的 ${selectedRows.value.length} 个栏目中，${visibleCount} 个显示，${hiddenCount} 个隐藏。确定要统一切换状态吗？`,
    '批量切换状态',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const promises = selectedRows.value.map(row => 
        categoryApi.updateStatus(row.id, { isVisible: !row.isVisible })
      )
      
      await Promise.all(promises)
      
      ElNotification({
        title: '批量操作成功',
        message: `成功切换 ${selectedRows.value.length} 个栏目的显示状态`,
        type: 'success'
      })
      selectedRows.value = []
      await fetchCategoryList()
    } catch (error) {
      ElMessage.error('批量操作失败')
    }
  })
}

const handleBatchShow = async () => {
  if (!hasUpdatePermission.value) {
    ElMessage.error('权限不足，无法修改分类状态')
    return
  }
  
  try {
    const promises = selectedRows.value.map(row => 
      categoryApi.updateStatus(row.id, { isVisible: true })
    )
    
    await Promise.all(promises)
    
    ElNotification({
      title: '批量显示成功',
      message: `成功显示 ${selectedRows.value.length} 个栏目`,
      type: 'success'
    })
    selectedRows.value = []
    await fetchCategoryList()
  } catch (error) {
    ElMessage.error('批量显示失败')
  }
}

const handleBatchHide = async () => {
  if (!hasUpdatePermission.value) {
    ElMessage.error('权限不足，无法修改分类状态')
    return
  }
  
  try {
    const promises = selectedRows.value.map(row => 
      categoryApi.updateStatus(row.id, { isVisible: false })
    )
    
    await Promise.all(promises)
    
    ElNotification({
      title: '批量隐藏成功',
      message: `成功隐藏 ${selectedRows.value.length} 个栏目`,
      type: 'success'
    })
    selectedRows.value = []
    await fetchCategoryList()
  } catch (error) {
    ElMessage.error('批量隐藏失败')
  }
}

const handleBatchExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要导出的栏目')
    return
  }
  
  // 导出功能实现
  const exportData = selectedRows.value.map(row => ({
    id: row.id,
    name: row.name,
    englishName: row.englishName,
    description: row.description,
    level: row.level,
    sort: row.sort,
    isVisible: row.isVisible ? '显示' : '隐藏',
    allowSubmit: row.allowSubmit ? '允许' : '禁止',
    createTime: formatDate(row.createTime)
  }))
  
  // 简单的CSV导出
  const csvContent = [
    ['ID', '栏目名称', '英文名称', '描述', '级别', '排序', '显示状态', '允许投稿', '创建时间'],
    ...exportData.map(row => Object.values(row))
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `分类数据导出_${new Date().toLocaleDateString()}.csv`
  link.click()
  
  ElMessage.success('导出成功')
}

const handleExportSingle = (row) => {
  const exportData = [{
    id: row.id,
    name: row.name,
    englishName: row.englishName,
    description: row.description,
    level: row.level,
    sort: row.sort,
    isVisible: row.isVisible ? '显示' : '隐藏',
    allowSubmit: row.allowSubmit ? '允许' : '禁止',
    createTime: formatDate(row.createTime)
  }]
  
  const csvContent = [
    ['ID', '栏目名称', '英文名称', '描述', '级别', '排序', '显示状态', '允许投稿', '创建时间'],
    ...exportData.map(item => Object.values(item))
  ].map(item => item.join(',')).join('\n')
  
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `分类${row.name}_${new Date().toLocaleDateString()}.csv`
  link.click()
  
  ElMessage.success('导出成功')
}

const handleViewArticles = (row) => {
  // 跳转到文章管理页面，并按分类筛选
  ElMessage.info(`查看分类"${row.name}"下的文章功能开发中...`)
}

const handleTableSettings = () => {
  ElMessage.info('表格设置功能开发中...')
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleVisibilityChange = async (row) => {
  if (!hasUpdatePermission.value) {
    ElMessage.error('权限不足，无法修改显示状态')
    row.isVisible = !row.isVisible // 恢复原状态
    return
  }
  
  try {
    row.loading = true
    const response = await categoryApi.updateStatus(row.id, {
      isVisible: row.isVisible
    })
    if (response.code === 200) {
      ElMessage.success(`${row.isVisible ? '显示' : '隐藏'}成功`)
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    row.isVisible = !row.isVisible // 恢复原状态
  } finally {
    row.loading = false
  }
}

const handleSortChange = async (row) => {
  if (!hasUpdatePermission.value) {
    ElMessage.error('权限不足，无法修改排序')
    row.sort = row.originalSort // 恢复原值
    return
  }
  
  // 防抖处理
  if (row.sortTimer) {
    clearTimeout(row.sortTimer)
  }
  
  row.sortTimer = setTimeout(async () => {
    try {
      const response = await categoryApi.updateSort(row.id, {
        sort: row.sort
      })
      if (response.code === 200) {
        row.originalSort = row.sort
        ElMessage.success('排序更新成功')
        await fetchCategoryList()
      }
    } catch (error) {
      ElMessage.error('排序更新失败')
      row.sort = row.originalSort // 恢复原值
    }
  }, 1000)
}

const handleSortBlur = (row) => {
  // 失去焦点时立即保存
  if (row.sortTimer) {
    clearTimeout(row.sortTimer)
    handleSortChange(row)
  }
}

const handlePageChange = (page) => {
  queryParams.page = page
  fetchCategoryList()
}

const handlePageSizeChange = (size) => {
  queryParams.size = size
  queryParams.page = 1
  fetchCategoryList()
}

const handleDialogSuccess = () => {
  dialogVisible.value = false
  fetchCategoryList()
}
</script>

<style scoped>
.category-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 权限警告 */
.permission-alert {
  margin-bottom: 20px;
}

.permission-content {
  line-height: 1.6;
}

.permission-content ul {
  margin: 8px 0;
  padding-left: 20px;
}

.permission-content li {
  margin: 4px 0;
}

.permission-content code {
  background-color: #f1f2f3;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  color: #e74c3c;
}

/* 工具栏 */
.toolbar {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

/* 统计卡片 */
.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  border: none;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 表格容器 */
.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.table-toolbar {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fafafa;
}

.table-toolbar .toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toolbar-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.table-toolbar .toolbar-right {
  display: flex;
  gap: 8px;
}

/* 表格样式 */
.category-table {
  width: 100%;
}

.category-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name-text {
  font-weight: 500;
  color: #333;
  flex: 1;
}

.level-tag {
  margin-left: 8px;
}

.hot-tag {
  margin-left: 4px;
}

.expand-icon {
  flex-shrink: 0;
}

.english-name {
  font-style: italic;
}

.action-buttons {
  display: flex;
  gap: 6px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

/* 自定义对话框样式 */
:deep(.category-detail-dialog) {
  max-width: 600px;
}

:deep(.category-detail-dialog .el-message-box__content) {
  text-align: left;
  max-height: 400px;
  overflow-y: auto;
}

:deep(.delete-confirm-dialog) {
  max-width: 450px;
}

/* Element Plus 组件样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
  border-bottom: 2px solid #ebeef5;
}

:deep(.el-table .el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f8f9ff;
}

:deep(.el-table .el-table__expanded-cell) {
  background-color: #f9f9f9;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #67c23a;
}

:deep(.el-dropdown-menu) {
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-tag) {
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .action-buttons {
    gap: 4px;
  }
}

@media (max-width: 1200px) {
  .category-container {
    padding: 15px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

@media (max-width: 768px) {
  .category-container {
    padding: 10px;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 12px;
    padding: 12px;
  }
  
  .toolbar-left,
  .toolbar-right {
    width: 100%;
  }
  
  .toolbar-left {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .table-toolbar {
    padding: 12px;
    flex-direction: column;
    gap: 8px;
  }
  
  .table-toolbar .toolbar-left,
  .table-toolbar .toolbar-right {
    width: 100%;
    justify-content: center;
  }
  
  .stats-cards :deep(.el-col) {
    margin-bottom: 12px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 2px;
  }
  
  .action-buttons .el-button {
    margin: 0;
    width: 32px;
    height: 32px;
  }
}

/* 动画效果 */
.category-table {
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

:deep(.el-loading-spinner .circular) {
  width: 32px;
  height: 32px;
}
</style>